import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, Statistic, Tabs, Button, Spin } from 'antd';
import { Line, Pie, Column } from '@ant-design/plots';
import { PageContainer } from '@ant-design/pro-components';
import { api } from '@/services/api';

const { Option } = Select;
const { TabPane } = Tabs;

const StatsPage: React.FC = () => {
  const [timeRange, setTimeRange] = useState<number>(7);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await api.navigation.navigationStatsList({ days: timeRange });
        console.log(response)
        setData(response);
      } catch (error) {
        console.error('Failed to fetch stats:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
    
  }, [timeRange]);

  const dailyData = data?.[0]?.dailyStats?.map((item) => ({
    date: item.createdAt__date,
    visits: item.visitCount,
  }));

  const hourlyData = data?.[0]?.hourlyStats?.map((item) => ({
    hour: `${item.hour}时`,
    visits: item.visitCount,
  }));

  const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const weekdayData = data?.[0]?.weekdayStats?.map((item) => ({
    weekday: weekdayMap[item.weekday],
    visits: item.visitCount,
  }));

  const categoryData = data?.[0]?.categoryStats?.map((item) => ({
    type: item.name,
    value: item.visitCount,
  }));

  const tagData = data?.[0]?.tagStats?.map((item) => ({
    type: item.name,
    value: item.visitCount,
  }));

  if (loading) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card>
            <Row gutter={16} align="middle">
              <Col>
                <Select
                  value={timeRange}
                  onChange={setTimeRange}
                  style={{ width: 120 }}
                >
                  <Option value={7}>最近7天</Option>
                  <Option value={30}>最近30天</Option>
                  <Option value={90}>最近90天</Option>
                </Select>
              </Col>
              <Col>
                <Button type="link" onClick={() => window.location.href = '/navigation/links'}>
                  管理链接
                </Button>
              </Col>
              <Col flex="auto" />
              <Col>
                <Statistic title="总访问次数" value={data?.[0]?.totalVisits || 0} />
              </Col>
            </Row>
          </Card>
        </Col>

        <Col span={24}>
          <Card>
            <Tabs defaultActiveKey="daily">
              <TabPane tab="每日趋势" key="daily">
                {dailyData && (
                  <Line
                    data={dailyData}
                    xField="date"
                    yField="visits"
                    smooth
                    point
                  />
                )}
              </TabPane>
              <TabPane tab="时段分布" key="hourly">
                {hourlyData && (
                  <Column
                    data={hourlyData}
                    xField="hour"
                    yField="visits"
                  />
                )}
              </TabPane>
              <TabPane tab="星期分布" key="weekday">
                {weekdayData && (
                  <Column
                    data={weekdayData}
                    xField="weekday"
                    yField="visits"
                  />
                )}
              </TabPane>
            </Tabs>
          </Card>
        </Col>

        <Col span={8}>
          <Card title="分类访问统计">
            {categoryData && (
              <Pie
                data={categoryData}
                angleField="value"
                colorField="type"
                radius={0.8}
                label={{ type: 'outer' }}
              />
            )}
          </Card>
        </Col>

        <Col span={8}>
          <Card title="标签访问统计">
            {tagData && (
              <Pie
                data={tagData}
                angleField="value"
                colorField="type"
                radius={0.8}
                label={{ type: 'outer' }}
              />
            )}
          </Card>
        </Col>

        <Col span={8}>
          <Card title="最常访问的链接">
            {data?.[0]?.popularLinks?.map((link) => (
              <div key={link.id} style={{ marginBottom: 8 }}>
                <a href={link.url} target="_blank" rel="noopener noreferrer">
                  {link.title}
                </a>
                <span style={{ marginLeft: 8, color: '#999' }}>
                  访问次数：{link.visitCount}
                </span>
              </div>
            ))}
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default StatsPage;
